/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "gpu.h"
#include <mc/log.h>

namespace dev {
bool Gpu::read_gpu_temperature(postbox_ptr postbox) {
    if (!postbox) {
        elog("Gpu temperature: postbox not initialized");
        TemperatureCelsius.set_value(static_cast<double>(32768));
        return false;
    }
    try {
        SMBusPostboxProtocol::RequestParams params;
        params.name           = "CardTemperature";
        params.opcode         = 0x02; // Get Temperature
        params.arg1           = 0x00; // Sensor on primary GPU (GPU_0)
        params.arg2           = 0x0;  // Unused
        params.capa_dword_num = 0;    // No capability check needed
        params.capa_mask      = 0x0;  // No capability check needed
        params.data_out       = true;
        params.data_len       = 4;
        params.data_type      = SMBusPostboxProtocol::KEEP_DIGITAL;
        params.data_mask      = 0xFFFFFFFF; // Read the full 32-bit value

        std::string result_str = postbox->sendRequest(params);
        if (result_str.empty()) {
            elog("CardTemperature: empty response when reading CardTemperature");
            TemperatureCelsius.set_value(0);
            return false;
        }
        int32_t raw_value   = std::stoi(result_str);
        int16_t temperature = (raw_value >> 16) & 0xFFFF;
        elog("CardTemperature read: 0x${CardTemperature:02x}", ("CardTemperature", temperature));
        try {
            TemperatureCelsius.set_value(temperature);
        } catch (const std::exception& e) {
            TemperatureCelsius.set_value(0);
            elog("CardTemperature Set value failed: ${error}", ("error", e.what()));
        }
        return true;
    } catch (const std::exception& e) {
        elog("CardTemperature: exception when reading CardTemperature: ${e}", ("e", e.what()));
        TemperatureCelsius.set_value(0);
        return false;
    }
}

bool Gpu::read_card_builddate(postbox_ptr postbox) {
    if (!postbox) {
        elog("CardBuildDate: postbox not initialized");
        return false;
    }
    try {
        SMBusPostboxProtocol::RequestParams params;
        params.name           = "CardBuildDate";
        params.opcode         = 0x5;
        params.arg1           = 0x7;
        params.arg2           = 0x0;
        params.capa_dword_num = 1;
        params.capa_mask      = 0x00000080;
        params.data_out       = true;
        params.data_len       = 4;
        params.data_type      = SMBusPostboxProtocol::ARRAY_TO_ASCII_LITTLEENDIAN;
        params.data_mask      = 0xffffffff;

        std::string result_str = postbox->sendRequest(params);
        if (result_str.empty()) {
            elog("CardBuildDate: empty response");
            return false;
        }
        elog("CardBuildDate read: ${CardBuildDate}", ("CardBuildDate", result_str));
        try {
            BuildDate.set_value(result_str);
        } catch (const std::exception& e) {
            elog("CardBuildDate Set value failed: ${error}", ("error", e.what()));
        }
        return true;
    } catch (const std::exception& e) {
        elog("CardBuildDate: exception when reading CardBuildDate: ${e}", ("e", e.what()));
        return false;
    }
}

bool Gpu::read_infoRomVersion(postbox_ptr postbox) {
    if (!postbox) {
        elog("CardInfoRomVersion: postbox not initialized");
        return false;
    }
    try {
        SMBusPostboxProtocol::RequestParams params;
        params.name           = "CardInfoRomVersion";
        params.opcode         = 0x5;
        params.arg1           = 0x0e;
        params.arg2           = 0x0;
        params.capa_dword_num = 1;
        params.capa_mask      = 0x00004000;
        params.data_out       = true;
        params.data_len       = 16;
        params.data_type      = SMBusPostboxProtocol::KEEP_ASCII;
        params.data_mask      = 0xffffffff;

        std::string result_str = postbox->sendRequest(params);
        if (result_str.empty()) {
            elog("CardInfoRomVersion: empty response");
            return false;
        }
        elog("CardInfoRomVersion read: ${CardInfoRomVersion}", ("CardInfoRomVersion", result_str));
        try {
            InfoRomVersion.set_value(result_str);
        } catch (const std::exception& e) {
            elog("CardInfoRomVersion Set value failed: ${error}", ("error", e.what()));
        }
        return true;
    } catch (const std::exception& e) {
        elog("CardInfoRomVersion: exception when reading CardInfoRomVersion: ${e}",
             ("e", e.what()));
        return false;
    }
}

bool Gpu::read_uuid(postbox_ptr postbox) {
    if (!postbox) {
        elog("Gpu.read_uuid: postbox not initialized");
        return false;
    }
    try {
        SMBusPostboxProtocol::RequestParams params;
        params.name           = "CardUUID";
        params.opcode         = 0x5;
        params.arg1           = 0xd;
        params.arg2           = 0x0;
        params.capa_dword_num = 1;
        params.capa_mask      = 0x00002000;
        params.data_out       = true;
        params.data_len       = 16;
        params.data_type      = SMBusPostboxProtocol::ARRAY_TO_ASCII_BIGENDIAN;
        params.data_mask      = 0xffffffff;

        std::string hex32 = postbox->sendRequest(params);
        if (hex32.empty()) {
            elog("Gpu.read_uuid: empty response");
            return false;
        }
        if (hex32.size() != 32) {
            elog("Gpu.read_uuid: invalid hex length=${len}, data='${data}'",
                 ("len", hex32.size())("data", hex32));
            return false;
        }
        // 分段: 8-4-4-4-12
        std::string seg1     = hex32.substr(0, 8);
        std::string seg2     = hex32.substr(8, 4);
        std::string seg3     = hex32.substr(12, 4);
        std::string seg4     = hex32.substr(16, 4);
        std::string seg5     = hex32.substr(20, 12);
        std::string uuid_fmt = "GPU-" + seg1 + "-" + seg2 + "-" + seg3 + "-" + seg4 + "-" + seg5;

        try {
            UUID.set_value(uuid_fmt);
        } catch (const std::exception& e) {
            elog("Gpu.read_uuid: set UUID failed: ${err}", ("err", e.what()));
        }
        elog("Gpu.read_uuid: uuid=${uuid}", ("uuid", uuid_fmt));
        return true;
    } catch (const std::exception& e) {
        elog("Gpu.read_uuid: exception=${err}", ("err", e.what()));
        return false;
    }
}
} // namespace dev

MC_REFLECT(dev::Gpu)
